package com.seven.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author seven
 **/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        //设置静态资源不要拦截
        web.ignoring().antMatchers("/js/**","/cs/**","/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        //定制请求的授权规则
        http.authorizeRequests()
                //首页，所有请求都允许
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3");
        //开启自动配置的登录功能，默认请求是/login
        http.formLogin();
        //1、/login来到登陆页
        //2、重定向到/login?error表示登陆失败
        //3、更多详情，请看源码解释
        //开启自动配置注销功能
        //访问/logout表示用户注销，清空session
        //.logoutUrl("/")退出成功后返回的地址
        http.logout().logoutUrl("/");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
        auth.inMemoryAuthentication()
                //这里不允许使用明文
                //这样，页面提交时候，密码不是以明文的方式进行匹配，如果是明文就会报错
                .passwordEncoder(
                        new MyPasswordEncoder()).withUser("admin").password("admin").roles("VIP1","VIP2","VIP3")
                .and()
                .passwordEncoder(
                        new MyPasswordEncoder()).withUser("guest").password("guest").roles("VIP1")
                .and()
                .passwordEncoder(
                        new MyPasswordEncoder()).withUser("seven").password("seven").roles("VIP1","VIP2");
    }
    //简单的加密
    public class MyPasswordEncoder implements PasswordEncoder {
        @Override
        public String encode(CharSequence charSequence) {
            return charSequence.toString();
        }

        @Override
        public boolean matches(CharSequence charSequence, String s) {
            return s.equals(charSequence.toString());
        }
    }
}
